

registSwiper(".swiper", ".wrapper", ".slider", ".counter button")

/**
 * 
 * @param {string} container 最外层容器
 * @param {string} wrapper 包裹器,内容应被平铺
 * @param {string} sliders swiper item 每一个单独的slider
 * @param {string}  counters 计数器列表
 */
function registSwiper(container, wrapper, sliders, counters, timeout = 4000) {
  let containerNode = document.querySelector(container)
  let sliderNodes = document.querySelectorAll(sliders)
  let wrapperNode = document.querySelector(wrapper)
  let counterNodes = document.querySelectorAll(counters)
  let containerWidth = 0;
  let containerHeight = 0;
  let current = 0;
  let length = sliderNodes.length;
  let timeoutTimer;
  wrapperNode.style.transition = "all 1s ease"

  window.addEventListener("load", () => {
    commitResize();
  })

  window.onresize = (e) => {
    commitResize();
  }

  /**
   * 为按钮组添加点击事件
   * 暂时取消定时器,避免抖动
   * 调整动画速度
   */
  counterNodes.forEach((node, index) => {
    node.addEventListener("click", () => {
      wrapperNode.style.transition = "all 0.5s ease"
      translateToCurrent(index)
      clearInterval(intervalTimer)
      clearTimeout(timeoutTimer);
      timeoutTimer = setTimeout(() => {
        wrapperNode.style.transition = "all 1s ease"
        intervalTimer = setInterval(() => {
          current = (++current) % length;
          translateToCurrent(current)
        }, timeout);
      }, 500);
    })
  })

  let intervalTimer = setInterval(() => {
    current = (++current) % length;
    translateToCurrent(current)
  }, timeout);
  /**
   * 缩放时更改包裹容器大小和translate距离
   */
  function commitResize() {
    containerHeight = containerNode.offsetHeight
    containerWidth = containerNode.offsetWidth
    sliderNodes.forEach(node => {
      node.style.height = containerHeight + "px"
      node.style.width = containerWidth + "px"
    })
  }
  /**
   * wrapper 移动到当前slider
   * @param {number} index 
   */
  function translateToCurrent(index) {
    current = index
    wrapperNode.style.transform = `translateX(-${current * containerWidth}px)`
    counterNodes.forEach((node, index) => {
      current === index
        ? node.classList.add("active")
        : node.classList.remove("active")
    })
  }
}
